/*
 * @Author: luofeng
 * @Date: 2021-10-26 10:30:18
 * @LastEditTime: 2021-10-26 10:32:32
 * @LastEditors: luofeng
 * @Description: In User Settings Edit
 */
import { getQueryVariable, delParam, setSessionStore, getSessionStore } from '@/utils/common.js'
import { WEIXIN_APP_ID } from '@/config'

const wechatConfig = {
  // 通过微信授权，微信返回code参数
  code: getQueryVariable('code') || '',
  // 本地调试链接带openid参数
  queryOpenId: getQueryVariable('queryOpenId') || getQueryVariable('openId') || '',
  // 保存在本地openid
  sessionOpenId: getSessionStore('sessionOpenId'),
  // 保存在本地个人微信授权信息
  sessionWxUserInfo: getSessionStore('sessionWxUserInfo') || {},
  getUserInfoByCode(vm) {
  
    if (!getApp().globalData.isWeixinBrowser) {
      return Promise.resolve('')
    }
    
    return new Promise((resolve, reject) => {
      // 本地调试
      if (this.queryOpenId) {
        setSessionStore('sessionOpenId', this.queryOpenId)
        resolve({ openId: this.queryOpenId })
        return
      }
      if (this.sessionOpenId) {
        resolve(this.sessionWxUserInfo)
        return
      }
      if (this.code) {
        const params = {
          url: `${getApp().globalData.h5Url}${vm.$apiUrl.shareGetUserInfoByCode}`,
          method: 'POST',
          data: {
            code: this.code,
            channel: 'h5',
          },
        }
        vm.$request(params).then((res) => {
          if (res && res.success) {
            setSessionStore('sessionOpenId', res.data.openId)
            setSessionStore('sessionWxUserInfo', res.data.wxUserVO)
            resolve(res.data)
          } else {
            reject(res)
           
          }
        }, () => {
          reject()
        })
      } else {
        this.weixinAuthInit()
      }
    })
  },
  getOpenIdByCode(vm) {

    if (!getApp().globalData.isWeixinBrowser) {
      return Promise.resolve('')
    }

    return new Promise((resolve, reject) => {
      if (this.queryOpenId) {
        setSessionStore('sessionOpenId', this.queryOpenId)
        resolve({ openId: this.queryOpenId })
        return
      }

      if (this.sessionOpenId) {
        resolve(this.sessionWxUserInfo)
        return
      }

      if (this.code) {
        const params = {
          url: `${getApp().globalData.h5Url}${vm.$apiUrl.getOpenIdByCode}/${this.code}`,
        }
        vm.$request(params).then((res) => {
          if (res && res.success) {
            setSessionStore('sessionOpenId', res.data.openid)
            setSessionStore('sessionWxUserInfo', res.data)
            resolve(res.data)
          } else {
            reject()
          }
        }, () => {
          reject()
        })
      } else {
        this.weixinAuthInit()
      }

    })
  },
  weixinAuthInit()  {
    const mainHost = window.location.origin
    const appId = mainHost.includes('h5-test') ? WEIXIN_APP_ID.test : WEIXIN_APP_ID.prod
    const router = window.location.search
    let fullPath = mainHost + window.location.pathname + router
    if (router.includes('code')) {
      fullPath = delParam(fullPath, 'code')
      fullPath = delParam(fullPath, 'state')
    }
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(fullPath)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    location.href = url
  },
  weixinAuthInitLogin() {
    const mainHost = window.location.origin
    const appId = mainHost.includes('h5-test') ? WEIXIN_APP_ID.test : WEIXIN_APP_ID.prod
    const fullPath = mainHost + '/pages/main/pages/login/index'
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(fullPath)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    location.href = url
  },
  weiXinBrowerShare(vm) {

    if (!getApp().globalData.isWeixinBrowser) {
      return Promise.resolve('')
    }

    const url = window.location.href.split('#')[0]
    // const url = window.location.href
    
    const params = {
      url: `${getApp().globalData.weixinUrl}${vm.$apiUrl.jsticketV2}`,
      data: {
        url,
      },
    }
    let errorInfo = undefined
    return new Promise((resolve, reject) => {
      vm.$request(params).then((res) => {
        if (res && res.success) {
          const { data } = res
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: data.appId, // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.noncestr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名
            jsApiList: ['updateAppMessageShareData', 'onMenuShareAppMessage', 'updateTimelineShareData', 'onMenuShareTimeline'], // 必填，需要使用的JS接口列表
          })
          wx.error(function(res) {
            console.log(res, 'config---error')
            errorInfo = res
          })
          wx.ready(function() {
            console.log('process ready')
            if (errorInfo) {
              reject({ success: false, errorInfo })
            } else {
              console.log('process success')
              resolve({ success: true })
            }
          })
        } else {
          reject()
        }
      }, () => {
        reject()
      })
    })
  },
  buildShareContent(shareData) {

    if (!getApp().globalData.isWeixinBrowser) {
      return
    }
    
    wx.ready(function() {
      wx.updateAppMessageShareData({
        title: shareData.title, // 分享标题
        desc: shareData.desc,
        link: shareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareData.shareImg, // 分享图标
        success() {
        // 用户点击了分享后执行的回调函数
          console.log('分享成功-----updateAppMessageShareData')
        // successCallback && successCallback(1)
        },
        fail(res) {
          console.log(res, '分享失败-----updateAppMessageShareData')
        },
      })
      wx.onMenuShareAppMessage({
        title: shareData.title, // 分享标题
        desc: shareData.desc,
        link: shareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareData.shareImg, // 分享图标
        success() {
          console.log('分享成功-----onMenuShareAppMessage')
        },
        fail(res) {
          console.log(res, '分享失败-----onMenuShareAppMessage')
        },
      })
      wx.onMenuShareTimeline({
        title: shareData.title, // 分享标题
        link: shareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareData.shareImg, // 分享图标
        success() {
       
        },
        cancel() {
        // 用户取消分享后执行的回调函数
        },
      })
      // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
      wx.updateTimelineShareData({
        title: shareData.title, // 分享标题
        link: shareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareData.shareImg, // 分享图标
        success() {
       
        },
        cancel() {
        // 用户取消分享后执行的回调函数
        },
      })
    })
  },
}

export default wechatConfig